#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>

#define ARRAY_SIZE 200

#define SWAP_THESE(addr_1, addr_2, addr_swap)\
    if((addr_1) != (addr_2))\
    {\
        *(addr_swap) = *(addr_1);\
        *(addr_1) = *(addr_2);\
        *(addr_2) = *(addr_swap);\
    }

int get_random_num(int range[])
{
	return (random() % (range[1] - range[0]) + range[0]);
}

int partition(int *array, const int leftIndex, const int rightIndex,
	      const int pivotIndex)
{
	int storedIndex = leftIndex;
	int swap_space;
	SWAP_THESE(array + pivotIndex, array + rightIndex, &swap_space);

	int i = 0;
	for (i = leftIndex; i < rightIndex; i++) {
		if (array[i] < array[rightIndex]) {
			SWAP_THESE(&(array[i]), &(array[storedIndex]),
				   &swap_space);
			storedIndex++;
		}
	}

	SWAP_THESE(&(array[storedIndex]), &(array[rightIndex]), &swap_space);
	return storedIndex;
}

int *quick_sort(int *array, int leftIndex, int rightIndex)
{
	int pivotIndex = rightIndex;
	if (rightIndex > leftIndex) {
		pivotIndex =
		    partition(array, leftIndex, rightIndex, pivotIndex);

		quick_sort(array, leftIndex, pivotIndex - 1);
		quick_sort(array, pivotIndex + 1, rightIndex);
	}
	return array;
}

int main()
{
	int range[] = { 0, ARRAY_SIZE };
	int array[ARRAY_SIZE];
	int loop_count = 0;

	srandom(time(NULL));
	while (loop_count < ARRAY_SIZE) {
		printf("[%d] ", array[loop_count] = get_random_num(range));
		loop_count++;
	}
	putchar('\n');

	quick_sort(array, 0, ARRAY_SIZE - 1);

	loop_count = 0;
	while (loop_count < ARRAY_SIZE) {
		printf("[%d] ", array[loop_count]);
		loop_count++;
	}
	putchar('\n');

	return 0;
}
